<?php

namespace Theatre\Server;

class Theatre extends \Theatre\Controller {
	/**
	 * Get schedule for the selected date for the given partner
	 */
	public function getSchedule() {
		$this->view('JSON');

		$requestValid = $this->APIRequestIsValid($this->params);

		if ($requestValid['status'] == 'error') {
			$this->set($requestValid);

			return;
		}

		$partner = $requestValid['partner'];

		$ts = time();
		if (!empty($this->params['date'])) {
			$a = strptime($this->params['date'], '%Y-%m-%d');
			$a['tm_mon'] += 1;
			$a['tm_year'] += 1900;

			$ts = mktime(0, 0, 0, $a['tm_mon'], $a['tm_mday'], $a['tm_year']);

			if (empty($ts) || $ts <= 0) {
				$ts = time();
			}
		}

		$schedule = array();

		$results = $this->model('PostGreSQL')->dbRunResult(
			"getSchedule($1, $2, $3)",
			$partner->id,
			date('Y-m-d 00:00:00', $ts),
			date('Y-m-d 23:59:59', $ts)
		);

		while ($result = $this->model('PostGreSQL')->dbFetchObject($results)) {
			if (empty($schedule[$result->hall_id])) {
				$schedule[$result->hall_id] = array(
					'name'  => $result->hall_name,
					'shows' => array()
				);
			}

			$schedule[$result->hall_id]['shows'][$result->show_id] = array(
				'name'                => $result->show_name,
				'representation_id'   => $result->representation_id,
				'representation_date' => $result->show_date
			);
		}
		
		$this->set(array(
			'status'   => 'success',
			'schedule' => $schedule
		));
	}
}
